﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MonsterEngine.Entities;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson.Serialization;

namespace MonsterEngine.Adapters
{
    public class MongoAdapter<T>
    {
        private string collectionName = typeof(T).Name;

        private MongoDatabase GetDatabase()
        {
            MongoClient client = new MongoClient(Constants.MONGO_CONNECTION_STRING);
            MongoServer server = client.GetServer();
            MongoDatabase dataBase = server.GetDatabase(Constants.MONGO_DATABASE);
            return dataBase;
        }

        public List<T> GetListObjects()
        {
            return GetDatabase().GetCollection<T>(collectionName).FindAll().ToList<T>();
        }

        public List<T> GetListObjects(string objectField, string objectValue)
        {
            var qry = Query.EQ(objectField, objectValue);
            return GetDatabase().GetCollection<T>(collectionName).FindAs<T>(qry).ToList<T>();
        }

        public List<T> GetListObjects(IMongoQuery qry)
        {
            return GetDatabase().GetCollection<T>(collectionName).FindAs<T>(qry).ToList<T>();
        }

        public List<T> GetListLimitedObjects(IMongoQuery qry, IMongoSortBy srt)
        {
            var results = GetDatabase().GetCollection<T>(collectionName).FindAs<T>(qry);
            results.SetSortOrder(srt);
            results.SetLimit(Constants.MONGO_MAX_SEARCH_RESULTS);

            return results.ToList();
        }
       
        public T GetSingleObject(string objectId)
        {
            var qry = Query.EQ("_id", objectId);
            return GetDatabase().GetCollection<T>(collectionName).FindOne(qry);
        }

        public bool UpdateSingleObject(object mongmong)
        {
            return GetDatabase().GetCollection<T>(collectionName).Save(mongmong).UpdatedExisting;
        }

        public void InsertObject(T mObject)
        {
            MongoCollection<T> collection = GetDatabase().GetCollection<T>(collectionName);

            collection.Insert(mObject);
        }
    }
}